import { defineStore } from 'pinia'
import http from '@/utils/http'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: localStorage.getItem('access_token') || '',
    user: null,
    loading: false,
    error: ''
  }),
  getters: {
    isAuthenticated: (state) => Boolean(state.accessToken)
  },
  actions: {
    async login(username, password) {
      this.loading = true
      this.error = ''
      try {
        const { data } = await http.post('/auth/login', { username, password })
        const token = data?.access_token
        if (!token) throw new Error('登录失败：无令牌返回')
        this.accessToken = token
        localStorage.setItem('access_token', token)
        await this.fetchProfile()
        return true
      } catch (err) {
        this.error = err?.response?.data?.detail || err.message || '登录失败'
        throw err
      } finally {
        this.loading = false
      }
    },
    async register(username, password) {
      this.loading = true
      this.error = ''
      try {
        await http.post('/auth/register', { username, password })
        return true
      } catch (err) {
        this.error = err?.response?.data?.detail || err.message || '注册失败'
        throw err
      } finally {
        this.loading = false
      }
    },
    async fetchProfile() {
      try {
        const { data } = await http.get('/auth/profile')
        this.user = data
      } catch (err) {
        // ignore
      }
    },
    logout() {
      this.accessToken = ''
      this.user = null
      localStorage.removeItem('access_token')
    }
  }
})


